#!/usr/bin/env python
# -*- coding: utf-8 -*-

from BeautifulSoup import BeautifulSoup 
from random import randrange
import re

DEBUG = False

class Analyse:
    villages = {}
    villagesIdx = None

    Perfil = {}

    def __init__(self, source):
        self.source = source
        self.getVillages()


    def getVillages(self):
        self.villages = {}

        soup = BeautifulSoup(self.source)
        allA = soup.findAll('a')

        for al in allA:
            if "?newdid" in al.attrs[0][1]:
                self.villages[int(al.attrs[0][1].split("=")[1])] = \
                    (al.contents[0],al.attrs[0][1])

        self.villagesIdx = self.villages.keys()
        self.villagesIdx.sort()


    def getPerfil(self, source=None, url=None):
        if not(source):
            return False

        user_id = int(url.split("=")[1])

        soup = BeautifulSoup(source)
        allTr = soup.findAll('tr', {'class':'s7'})

        Perfil = {}

        td = allTr[0]('td')
        Perfil['Tribo'] = td[1].contents[0]

        td = allTr[1]('td')
        try:
            Perfil['Ally'] = td[1]('a')[0].contents[0]
        except IndexError, e:
            Perfil['Ally']=None

        td = allTr[3]('td')
        Perfil['Pop'] = td[1].contents[0]

        villages={}
        table = soup.findAll('table', {'class':'tbg'})
        for idx in range(2, len(table[1]('tr'))):
            name=table[1]('tr')[idx]('td')[0].findAll('a')[0].contents[0]
            try:
                xpto=table[1]('tr')[idx]('td')[0].findAll('span')[0].contents[0]
                cap=True
            except IndexError, e:
                cap=False
            pop=table[1]('tr')[idx]('td')[1].contents[0]
            xy=table[1]('tr')[idx]('td')[2].contents[0]
            villages[name]={
                'name': name,
                'capital': cap,
                'pop':  pop,
                'xy':   xy,
                }

        Perfil['villages']=villages
        self.Perfil = Perfil
        self.user_id = user_id

        if len(villages)>1:
            ovillages = self.villages
            self.villages = {}
            for idx in self.villagesIdx:
                a = villages[ovillages[idx][0]]
                self.villages[idx]=(ovillages[idx][0],ovillages[idx][1],
                                   a['capital'],a['pop'],a['xy'])
                self.Perfil['villages'][ovillages[idx][0]]['link']=ovillages[idx][1]
                if a['capital']:
                    self.Perfil['capital']=(idx,ovillages[idx][0],ovillages[idx][1],
                                    a['capital'],a['pop'],a['xy'])
        elif len(villages)==1:
            self.Perfil['capital']=(0,name,'dorf1.php',True,pop,xy)
                        
        return self.Perfil



